import React, { useEffect, useState, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button, Card, Divider, message, Modal, DatePicker, Drawer, Spin, Space } from 'antd';
import { ShoppingCartOutlined, BookOutlined, RobotOutlined, CloseOutlined, UserOutlined, OpenAIOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';
import type { RootState } from '../../store';
import Header from "../../components/Header/Header.tsx";
import Comments from "../../components/Comments";
import image from "../../assets/s34522268.jpg";
import defaultBookCover from "../../assets/s34522268.jpg";
import { getBookById } from "../../api/bookController.ts";
import { addBookBorrow } from "../../api/bookBorrowController.ts";
import { Bubble, Sender, XStream } from '@ant-design/x';
import CryptoJS from 'crypto-js';
import { Viewer } from '@bytemd/react';
import gfm from '@bytemd/plugin-gfm';
import highlight from '@bytemd/plugin-highlight';
import 'bytemd/dist/index.css';
import 'highlight.js/styles/default.css';
import { listAiPrompt } from '../../api/aiPromptController';

interface BookDetailType {
    id: number;
    image: string;
    title: string;
    author: string;
    isbn: string;
    publisher: string;
    publishDate: string;
    price: number;
    stock: number;
    description: string;
    createTime: string;
}

// 添加生成MD5的工具函数
const generateMD5 = () => {
    const timestamp = new Date().getTime().toString();
    const randomStr = Math.random().toString();
    return CryptoJS.MD5(timestamp + randomStr).toString().toUpperCase();
};

// 添加 ByteMD 插件配置
const plugins = [
    gfm(),
    highlight(),
];

// 修改 ChatMessage 接口
interface ChatMessage {
    id: number;
    placement: 'start' | 'end';
    content: string;  // 改为只接受字符串类型
    icon: JSX.Element;
    flag: boolean;
}

// 添加新的接口定义
interface Prompt {
    id: string;
    prompttitle: string;
    promptcontent: string;
    createtime: string;
    updatetime: string;
    isdelete: number;
}

export default function BookDetail() {
    const { id } = useParams();
    const navigate = useNavigate();
    const loginUser = useSelector((state: RootState) => state.loginUser);
    const [book, setBook] = useState<BookDetailType | null>(null);
    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [borrowDate, setBorrowDate] = useState<string>('');
    const [returnDate, setReturnDate] = useState<string>('');
    const [isAIChatOpen, setIsAIChatOpen] = useState(false);
    const [chatValue, setChatValue] = useState('');
    const [chatLoading, setChatLoading] = useState(false);
    const [sessionId] = useState(() => generateMD5());
    const [chatMessages, setChatMessages] = useState<ChatMessage[]>([
        {
            id: 1,
            placement: 'end',
            content: '你好！我是AI助手，很高兴为您解答关于这本书的任何问题。',
            icon: <UserOutlined />,
            flag: true,
        }
    ]);
    const [prompts, setPrompts] = useState<Prompt[]>([]);
    const [selectedPrompt, setSelectedPrompt] = useState<Prompt | null>(null);
    const [showPromptList, setShowPromptList] = useState(false);
    const [isClosing, setIsClosing] = useState(false);
    const messagesContainerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const fetchBookDetail = async () => {
            try {
                const response = await getBookById({ id: Number(id) });
                if (response.code === 200 && response.data) {
                    // 转换API返回的数据格式为组件所需格式
                    setBook({
                        id: Number(response.data.id),
                        image: response.data.imageurl,
                        title: response.data.bookname,
                        author: response.data.bookauthor,
                        isbn: response.data.isbn,
                        publisher: response.data.publisher,
                        publishDate: response.data.publishdate.split(' ')[0],
                        price: response.data.price,
                        stock: response.data.stock,
                        description: response.data.bookdesc,
                        createTime: response.data.createtime
                    });
                }
            } catch (error) {
                console.error('获取图书详情失败:', error);
                message.error('获取图书详情失败');
            } finally {
                setLoading(false);
            }
        };

        if (id) {
            fetchBookDetail();
        }
    }, [id]);

    // 修改获取prompts的函数，使用aiPromptController
    const fetchPrompts = async () => {
        try {
            const response = await listAiPrompt();
            if (response.code === 200) {
                setPrompts(response.data);
            }
        } catch (error) {
            console.error('获取prompts失败:', error);
            message.error('获取提示词列表失败');
        }
    };

    // 在组件挂载时获取prompts
    useEffect(() => {
        fetchPrompts();
    }, []);

    // 添加点击外部关闭的处理函数
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            const target = event.target as HTMLElement;
            // 检查点击是否在提示词列表外部
            if (showPromptList && !target.closest('.prompt-list-container') && !target.closest('.prompt-trigger-btn')) {
                setIsClosing(true);
                setTimeout(() => {
                    setShowPromptList(false);
                    setIsClosing(false);
                }, 200);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [showPromptList]); // 只在 showPromptList 变化时重新添加监听器

    // 添加一个useEffect来处理滚动
    useEffect(() => {
        if (messagesContainerRef.current) {
            messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight;
        }
    }, [chatMessages]); // 当消息列表更新时触发滚动

    if (loading) {
        return (
            <>
                <Header />
                <div className="max-w-[1500px] mx-auto p-6">
                    <Card loading={true}></Card>
                </div>
            </>
        );
    }

    if (!book) {
        return (
            <>
                <Header />
                <div className="max-w-[1500px] mx-auto p-6">
                    <div className="text-center py-8">
                        <h2 className="text-xl text-gray-600">图书信息不存在</h2>
                    </div>
                </div>
            </>
        );
    }

    const handleBorrow = () => {
        if (!loginUser.id) {
            message.error('请先登录');
            return;
        }
        setIsModalOpen(true);
    };

    const handleModalOk = async () => {
        if (!borrowDate || !returnDate) {
            message.error('请选择借阅日期和归还日期');
            return;
        }

        // 计算借阅天数
        const startDate = new Date(borrowDate);
        const endDate = new Date(returnDate);
        const borrowDays = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));

        if (borrowDays <= 0) {
            message.error('归还日期必须晚于借阅日期');
            return;
        }

        if (borrowDays > 30) {
            message.error('借阅时间不能超过30天');
            return;
        }

        try {
            const borrowData = [{
                bookid: book?.id,
                bookname: book?.title,
                borrowtime: borrowDate,
                returntime: returnDate,
                borrowdays: borrowDays // 添加借阅天数
            }];

            const response = await addBookBorrow(borrowData);
            if (response.code === 200) {
                message.success('借阅成功');
                setIsModalOpen(false);
                // 跳转到我的图书页面，并传递查询参数
                navigate(`/my-books/${loginUser.id}?current=1&pageSize=10`);
            } else {
                message.error(response.msg || '借阅失败');
            }
        } catch (error) {
            console.error('借阅失败:', error);
            message.error('借阅失败，请稍后重试');
        }
    };

    const handleModalCancel = () => {
        setIsModalOpen(false);
        setBorrowDate('');
        setReturnDate('');
    };

    const handleAddToList = () => {
        if (!loginUser.id) {
            message.error('请先登录');
            return;
        }

        // 从 localStorage 获取现有书单
        const existingList = JSON.parse(localStorage.getItem('bookList') || '[]');
        
        // 检查是否已经在书单中
        const isExist = existingList.some((item: any) => item.id === book.id);
        if (isExist) {
            message.warning('该书籍已在书单中');
            return;
        }
        
        // 检查数量限制
        if (existingList.length >= 10) {
            message.warning('书单最多只能添加10本书，请先清理书单');
            return;
        }

        // 获取当前日期和明天的日期
        const today = new Date();
        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate() + 1);

        // 创建新的书单项
        const newBookItem = {
            id: book.id,
            bookName: book.title,
            author: book.author,
            cover: book.image || defaultBookCover,
            startDate: today.toISOString().split('T')[0],
            endDate: tomorrow.toISOString().split('T')[0],
            selected: false
        };

        // 更新 localStorage
        localStorage.setItem('bookList', JSON.stringify([...existingList, newBookItem]));
        message.success('已添加到书单');
    };

    const handleAIQuestion = () => {
        setIsAIChatOpen(true);
    };

    const handleCloseAIChat = () => {
        setIsAIChatOpen(false);
    };

    const fooAvatar: React.CSSProperties = {
        color: '#f56a00',
        backgroundColor: '#fde3cf',
    };

    const barAvatar: React.CSSProperties = {
        color: '#fff',
        backgroundColor: '#87d068',
    };

    const sendChatMessage = async () => {
        if (!chatValue.trim()) return;

        setChatLoading(true);
        const userMessage: ChatMessage = {
            id: chatMessages.length + 1,
            placement: 'start',
            content: chatValue,
            icon: <UserOutlined />,
            flag: false,
        };

        const aiMessage: ChatMessage = {
            id: chatMessages.length + 2,
            placement: 'end',
            content: '正在思考中...',
            icon: <UserOutlined />,
            flag: false,
        };

        setChatMessages(prev => [...prev, userMessage, aiMessage]);

        try {
            const messages = [
                {
                    content: "你是一个图书馆AI助手",
                    role: "system"
                }
            ];

            if (selectedPrompt) {
                const promptContent = selectedPrompt.promptcontent.replace('{{BOOK}}', book.title);
                messages.push({
                    content: promptContent,
                    role: "system"
                });
            }

            messages.push({
                content: chatValue,
                role: "user"
            });

            const chatRequest = {
                sessionId,
                messages
            };

            const response = await fetch('http://localhost:8081/api/ai/deepSeekChat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(chatRequest)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            if (response.body) {
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let shouldBreak = false;
                let currentMessage = '';
                let buffer = '';

                while (true) {
                    try {
                        const { done, value } = await reader.read();
                        if (done || shouldBreak) break;

                        buffer += decoder.decode(value, { stream: true });
                        const lines = buffer.split('\n');
                        buffer = lines.pop() || '';

                        for (const line of lines) {
                            if (line.startsWith('data:')) {
                                try {
                                    const jsonStr = line.slice(5).trim();
                                    if (jsonStr) {
                                        const parsedData = JSON.parse(jsonStr);
                                        if (parsedData.choices && parsedData.choices[0]) {
                                            const content = parsedData.choices[0].delta?.content || '';
                                            if (content) {
                                                currentMessage += content;
                                                await new Promise<void>(resolve => {
                                                    setChatMessages(prev => {
                                                        const updated = [...prev];
                                                        updated[updated.length - 1].content = currentMessage;
                                                        resolve();
                                                        return updated;
                                                    });
                                                });
                                            }
                                            
                                            if (parsedData.choices[0].finish_reason === 'stop') {
                                                shouldBreak = true;
                                                break;
                                            }
                                        }
                                    }
                                } catch (e) {
                                    console.error('解析响应数据失败:', e);
                                    throw new Error('解析响应数据失败');
                                }
                            }
                        }
                    } catch (error) {
                        console.error('读取流数据失败:', error);
                        throw error;
                    }
                }
            }
        } catch (error) {
            console.error('Error during message fetch:', error);
            message.error('消息发送失败');
            
            // 更新最后一条AI消息为错误提示
            setChatMessages(prev => {
                const updated = [...prev];
                updated[updated.length - 1].content = "服务器繁忙，请稍后再试";
                return updated;
            });
        } finally {
            setChatLoading(false);
            setChatValue('');
        }
    };

    // 修改处理点击的函数
    const handlePromptClick = () => {
        if (showPromptList) {
            setIsClosing(true);
            // 等待动画完成后再隐藏列表
            setTimeout(() => {
                setShowPromptList(false);
                setIsClosing(false);
            }, 200); // 与动画持续时间相匹配
        } else {
            setShowPromptList(true);
        }
    };

    // 修改处理选择的函数
    const handlePromptSelect = (prompt: Prompt) => {
        if (selectedPrompt?.id === prompt.id) {
            setIsClosing(true);
            setTimeout(() => {
                setSelectedPrompt(null);
                setShowPromptList(false);
                setIsClosing(false);
            }, 200);
        } else {
            setSelectedPrompt(prompt);
            setIsClosing(true);
            setTimeout(() => {
                setShowPromptList(false);
                setIsClosing(false);
            }, 200);
        }
    };

    return (
        <>
            <Header />
            <div className="max-w-[1500px] mx-auto p-6">
                <Card className="">
                    <div className="flex flex-col lg:flex-row gap-8">
                        {/* 左侧图书图片 */}
                        <div className="w-full lg:w-[300px] flex-shrink-0">
                            <img 
                                src={book.image} 
                                alt={book.title} 
                                className="w-full h-auto rounded-lg shadow-md mx-auto lg:mx-0"
                                style={{ maxWidth: '300px' }}
                                onError={(e) => {
                                    const target = e.target as HTMLImageElement;
                                    target.src = defaultBookCover;
                                }}
                            />
                        </div>

                        {/* 右侧信息区域 */}
                        <div className="flex-1">
                            {/* 标题和描述 */}
                            <h1 className="text-2xl font-bold mb-2">{book.title}</h1>
                            <p className="text-gray-600 mb-6">{book.description}</p>

                            {/* 图书信息网格 */}
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 bg-gray-50 p-4 rounded-lg mb-6">
                                <div className="flex items-center">
                                    <span className="text-gray-600 w-24">作者：</span>
                                    <span className="font-medium">{book.author}</span>
                                </div>
                                <div className="flex items-center">
                                    <span className="text-gray-600 w-24">ISBN：</span>
                                    <span className="font-medium">{book.isbn}</span>
                                </div>
                                <div className="flex items-center">
                                    <span className="text-gray-600 w-24">出版社：</span>
                                    <span className="font-medium">{book.publisher}</span>
                                </div>
                                <div className="flex items-center">
                                    <span className="text-gray-600 w-24">出版日期：</span>
                                    <span className="font-medium">{book.publishDate}</span>
                                </div>
                                <div className="flex items-center">
                                    <span className="text-gray-600 w-24">零售价：</span>
                                    <span className="font-medium text-red-500">￥{book.price}</span>
                                </div>
                                <div className="flex items-center">
                                    <span className="text-gray-600 w-24">剩余库存：</span>
                                    <span className="font-medium">{book.stock}本</span>
                                </div>
                            </div>

                            {/* 创建时间 */}
                            <div className="text-gray-500 text-sm mb-6">
                                创建时间：{book.createTime}
                            </div>

                            {/* 操作按钮 */}
                            <div className="flex flex-wrap gap-4 mb-6">
                                <Button 
                                    type="primary" 
                                    size="large" 
                                    icon={<ShoppingCartOutlined />} 
                                    onClick={handleBorrow}
                                >
                                    立即借阅
                                </Button>
                                <Button size="large" icon={<BookOutlined />} onClick={handleAddToList}>
                                    加入书单
                                </Button>
                                <Button size="large" icon={<RobotOutlined />} onClick={handleAIQuestion}>
                                    AI提问
                                </Button>
                            </div>

                            {/* 借阅须知 */}
                            <div className="bg-orange-50 p-4 rounded-lg">
                                <h3 className="text-lg font-bold text-orange-600 mb-2">借阅须知</h3>
                                <ul className="text-orange-600 text-sm list-disc list-inside space-y-1">
                                    <li>借阅书籍如果出现破损需借阅者承担借书全部费用</li>
                                    <li>默认可借阅30天</li>
                                    <li>逾期未归还图书会扣除信誉分</li>
                                    <li>信誉分低于50无法借阅图书</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </Card>

                {/* Add Modal component */}
                <Modal
                    title="借阅信息"
                    open={isModalOpen}
                    onOk={handleModalOk}
                    onCancel={handleModalCancel}
                    okText="确认借阅"
                    cancelText="取消"
                >
                    <div className="space-y-4">
                        <div className="flex flex-col space-y-2">
                            <label className="text-gray-600">借阅日期</label>
                            <DatePicker
                                className="w-full"
                                onChange={(date) => setBorrowDate(date ? date.format('YYYY-MM-DD') : '')}
                                disabledDate={(current) => current && current.valueOf() < Date.now()}
                            />
                        </div>
                        <div className="flex flex-col space-y-2">
                            <label className="text-gray-600">归还日期</label>
                            <DatePicker
                                className="w-full"
                                onChange={(date) => setReturnDate(date ? date.format('YYYY-MM-DD') : '')}
                                disabledDate={(current) => {
                                    const borrowMoment = borrowDate ? new Date(borrowDate).getTime() : Date.now();
                                    return current && (
                                        current.valueOf() < borrowMoment || 
                                        current.valueOf() > borrowMoment + 30 * 24 * 60 * 60 * 1000
                                    );
                                }}
                            />
                        </div>
                        <div className="text-sm text-gray-500">
                            注：最长借阅期限为30天
                        </div>
                    </div>
                </Modal>

                <Comments 
                    targetId={book.id} 
                    targetType={0}
                    currentUserId={loginUser.id}
                    defaultAvatar={loginUser.avatarUrl || '/path/to/default/avatar.png'}
                />

                {/* AI Chat Drawer */}
                <Drawer
                    title={
                        <div className="flex justify-between items-center">
                            <span>AI 智能问答</span>
                        </div>
                    }
                    placement="right"
                    onClose={handleCloseAIChat}
                    open={isAIChatOpen}
                    width={window.innerWidth < 1024 ? '100%' : 500}
                    className="lg:top-[64px]"
                    styles={{
                        body: {
                            padding: 0,
                            display: 'flex',
                            flexDirection: 'column',
                            height: '100%'
                        }
                    }}
                >
                    <div className="flex flex-col h-full">
                        <div 
                            ref={messagesContainerRef}
                            className="flex-1 overflow-y-auto p-4 scrollbar-thin scrollbar-thumb-gray-300 hover:scrollbar-thumb-gray-400 scrollbar-track-gray-100 scrollbar-thumb-rounded-full"
                        >
                            {chatMessages.map((message) => (
                                <Bubble
                                    key={message.id}
                                    placement={message.placement}
                                    content={
                                        message.placement === 'end' ? (
                                            <Viewer value={message.content} plugins={plugins} />
                                        ) : (
                                            message.content
                                        )
                                    }
                                    avatar={{
                                        icon: <UserOutlined />,
                                        style: message.placement === 'start' ? fooAvatar : barAvatar,
                                    }}
                                    header={message.placement === 'start' ? '你' : 'AI助手'}
                                    style={{ marginBottom: '10px', textAlign: 'left' }}
                                />
                            ))}
                        </div>

                        <div className="border-t p-4">
                            <Sender
                                value={chatValue}
                                loading={chatLoading}
                                onChange={(v) => setChatValue(v)}
                                onSubmit={sendChatMessage}
                                onCancel={() => {
                                    setChatLoading(false);
                                    message.error('取消发送!');
                                }}
                                prefix={(
                                    <div className="relative">
                                        <Button
                                            type={selectedPrompt ? "primary" : "default"}
                                            icon={<OpenAIOutlined />}
                                            onClick={handlePromptClick}
                                            className="prompt-trigger-btn"
                                        >
                                            <span className="truncate">
                                                {selectedPrompt ? selectedPrompt.prompttitle : '选择提示词'}
                                            </span>
                                        </Button>
                                        
                                        {showPromptList && (
                                            <div 
                                                className={`prompt-list-container absolute bottom-full left-0 bg-white border rounded-md shadow-xl mb-6 overflow-visible z-90 transform transition-all duration-200 ease-out origin-bottom ${
                                                    isClosing 
                                                        ? 'animate-slideDown opacity-0 translate-y-2' 
                                                        : 'animate-slideUp opacity-100 translate-y-0'
                                                } before:content-[''] before:absolute before:-bottom-2 before:left-1/2 before:-translate-x-1/2 before:w-4 before:h-4 before:bg-white before:rotate-45 before:border-r before:border-b before:border-gray-200 before:shadow-md`}
                                                style={{ 
                                                    width: '400px',
                                                    maxWidth: 'calc(100vw - 48px)'
                                                }}
                                            >
                                                <div className="relative bg-white rounded-md">
                                                <div className="max-h-[300px] overflow-y-auto scrollbar-hide">
                                                    {prompts.map(prompt => (
                                                        <div
                                                            key={prompt.id}
                                                            className={`p-3 cursor-pointer hover:bg-gray-50 transition-colors duration-150 ${
                                                                selectedPrompt?.id === prompt.id ? 'bg-blue-50' : ''
                                                            }`}
                                                            onClick={() => handlePromptSelect(prompt)}
                                                        >
                                                            <div className="font-medium text-sm text-gray-800 mb-1">
                                                                {prompt.prompttitle}
                                                            </div>
                                                            <div className="text-xs text-gray-500 line-clamp-2 mb-1">
                                                                {prompt.promptcontent}
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                                    <div className="h-3"></div>
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                )}
                                actions={(_, info) => {
                                    const { SendButton, LoadingButton, ClearButton } = info.components;
                                    return (
                                        <Space size="small">
                                            <ClearButton />
                                            {chatLoading ? (
                                                <LoadingButton type="default" icon={<Spin size="small" />} disabled />
                                            ) : (
                                                <SendButton type="primary" icon={<OpenAIOutlined />} disabled={!chatValue.trim()} />
                                            )}
                                        </Space>
                                    );
                                }}
                            />
                        </div>
                    </div>
                </Drawer>
            </div>
        </>
    );
} 